package subject_set.offer100;

/**
 * @author haomin
 * @date 2022/10/15 11:06
 **/
public class Offer29 {
    class Solution {
        public int[] spiralOrder(int[][] matrix) {
            if(matrix.length == 0 || matrix[0].length == 0) return new int[0];
            int[] res = new int[matrix.length * matrix[0].length];
            int l = 0, r = matrix[0].length-1, u = 0, d = matrix.length-1, ind = 0;
            while(true){
                for(int i = l; i <= r; ++i){
                    res[ind] = matrix[u][i]; ind++;
                }
                if(++u > d) break;
                for(int i = u; i <= d; ++i){
                    res[ind] = matrix[i][r]; ind++;
                }
                if(--r < l) break;
                for(int i = r; i >= l; --i){
                    res[ind] = matrix[d][i]; ind++;
                }
                if(--d < u) break;
                for(int i = d; i >= u; --i){
                    res[ind] = matrix[i][l]; ind++;
                }
                if(++l > r) break;
            }
            return res;
        }
    }
}